<?php

namespace app\common\model;

use app\helpers\Common;
use app\libs\traits\BaseModelTrait;

use think\model\concern\SoftDelete;

use think\facade\Db;

class AdminMenu extends Base
{
    /**
     * Base Model Trait
     */
    use BaseModelTrait;

    use SoftDelete;

    protected $deleteTime = 'deleted_at';

    // 软删除字段默认值
    protected $defaultSoftDelete = 0;

    // 当前模型名称 不带前缀
    protected $name = 'admin_menu';

    protected $pk = 'id';


    /**
     * Set sorting attribute
     *
     * @param $value
     * @return int
     */
    public function setSortingAttr($value)
    {
        return !empty($value) ? $value : 0;
    }

    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {
        foreach ($list as &$item) {
            $item = self::formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $params = '')
    {
        if (!$item) {
            return '';
        }

        if ($item['icon']) {
            $item['full_icon'] = full_file_url($item['icon']);
        }
        if (!$item['controller']) {
            $item['controller'] = '';
        }
        if (!$item['action']) {
            $item['action'] = '';
        }

        $item['route'] = $item['app'] . '/' . $item['controller'] . '/' . $item['action'];

        return $item;
    }

    /**
     * 按父ID查找菜单子项
     *
     * @param int $parentId 父菜单ID
     * @param bool $withSelf 是否包括他自己
     * @return array
     */
    public static function adminMenu($parentId, $withSelf = false)
    {
        // 父节点ID
        $parentId = (int) $parentId;
        $model = Db::name('admin_menu');
        $result = $model->where([['parent_id', '=', $parentId], ['status', '=', 1], ['type', '<>', 3]])->order('sorting', 'ASC')->select()->toArray();
        if ($withSelf) {
            $self[] = $model->where(['id' => $parentId])->find();
            $result = array_merge($self, $result);
        }

        $menus = [];
        foreach ($result as $item) {
            // 方法
            $action = $item['action'];

            // public开头的通过
            if (preg_match('/^public_/', $action)) {
                $menus[] = $item;
            } else {
                if (preg_match('/^ajax_([a-z]+)_/', $action, $match)) {
                    $action = $match[1];
                }

                $rule_name = strtolower($item['app'] . '/' . $item['controller'] . '/' . $action);
                // 检查权限
                if (true) {
                    $menus[] = $item;
                }
            }
        }

        return $menus;
    }

    // 取得树形结构的菜单
    public static function getTree($myId, $parent = '', $level = 1)
    {
        $data = self::adminMenu($myId);
        $level++;

        if (is_array($data)) {
            $result = null;
            foreach ($data as $item) {
                $id = $item['id'];
                $name = ucwords($item['app']);
                $model = $item['controller'] ? ucwords($item['controller']) : '';
                $action = $item['action'];
                // 附带参数
                $params = '';
                if (isset($item['param']) && $item['param']) {
                    $params = '?' . htmlspecialchars_decode($item['param']);
                }
                $menu = [
                    'app' => $item['app'],
                    'controller' => $item['controller'],
                    'action' => $item['action'],
                    'icon' => $item['icon'],
                    'id' => $id,
                    'name' =>  __($item['name']),
                    'target' => $item['target'],
                    'parent' => $parent,
                    'url' => (string)url(strtolower("{$name}/{$model}/{$action}{$params}")),
                    'lang' => strtoupper($name . '_' . $model . '_' . $action)
                ];
                $result[$id . $name] = $menu;
                $child = self::getTree($item['id'], $id, $level);
                // 后台管理界面只支持五层，超出的层级的不显示
                if ($child && $level <= 5) {
                    $result[$id . $name]['items'] = $child;
                }
            }

            return $result;
        }

        return false;
    }
}
